import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Popconfirm, Divider, Button, Input, Form, Space, Table, message } from 'antd';
import { connect } from 'umi';
import { SyncOutlined } from '@ant-design/icons';

const currControl = 'Edu_KeywordLib';
const { Search } = Input;
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      visible: false,
      selectedRowKeys: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      record: {},
      keywords: '',
      fileExt: [],
    };
  }
  componentDidMount() {
    this.fetchDatas();
  }
  fetchDatas = () => {
    this.setState({ loading: true });
    const { pageIndex, pageSize, keywords } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { skipCount: (pageIndex - 1) * pageSize, maxResultCount: pageSize, keywords },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var dataSource = resp.result.items;
          this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount });
        }
      });
  };
  handleDelete = (id: number) => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id },
        control: currControl,
      })
      .then(() => {
        this.fetchDatas();
      });
  };
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });
  };
  onSearch = (value: any) => {
    var keywords = this.state.keywords;
    keywords = value;
    this.setState({ keywords }, () => {
      this.fetchDatas();
    });
  };
  formRef: any = React.createRef();
  getData = (visible: boolean, record: any) => {
    if (record.id) {
      this.props
        .dispatch({
          type: 'Abp/get',
          payload: { id: record.id },
          control: currControl,
        })
        .then(() => {
          var result = this.props.response.result;
          this.setState({ record: result });
          this.formRef.current.setFieldsValue({ model: result });
        });
    }
  };
  onFinish = async (values: any) => {
    var act = 'Abp/update';
    const { record } = this.state;
    var model = record;
    model.correct_Keyword = values.model.correct_Keyword;
    this.props
      .dispatch({
        type: act,
        payload: model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.fetchDatas();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  render() {
    const { loading, dataSource, selectedRowKeys, totalCount, pageSize } = this.state;
    const columns: any = [
      {
        title: '序号',
        width: 60,
        align: 'center',
        key: 'index',
        render: (_: any, __: any, i: any) => {
          return i + 1;
        },
      },
      {
        title: '关键词',
        width: 260,
        dataIndex: 'keyword',
        ellipsis: true,
      },
      {
        title: '搜索量',
        width: 180,
        dataIndex: 'hits',
      },
      {
        title: '热度',
        width: 180,
        dataIndex: 'popularity',
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.id)}>
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.getData(true, record)}>编辑</a>
            </span>
          ) : null,
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <PageHeaderWrapper title={false}>
        <Card>
          <Space>
            <Button
              type="primary"
              onClick={this.fetchDatas}
              loading={loading}
              icon={<SyncOutlined />}
            >
              刷新
            </Button>

            <Search
              style={{ width: 240 }}
              placeholder="输入关键词搜索"
              allowClear
              onSearch={(value) => this.onSearch(value)}
            />
          </Space>
        </Card>
        <Card>
          <Form ref={this.formRef} layout="inline" onFinish={this.onFinish}>
            <Form.Item name={['model', 'keyword']} label="关键词" rules={[{ required: true }]}>
              <Input disabled />
            </Form.Item>
            <Form.Item
              name={['model', 'correct_Keyword']}
              label="纠正关键词"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
              <Button onClick={() => this.formRef.current.resetFields()}>重设</Button>
            </Space>
          </Form>
        </Card>
        <Table
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataSource}
          pagination={{
            onChange: (page) => {
              this.setState({ pageIndex: page }, () => {
                this.fetchDatas();
              });
            },
            pageSize,
            total: totalCount,
          }}
        />
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
